//
//  Client_RF225_qArticleController.swift
//  Wmsmobile
//
//  Created by xuNick on 16/9/11.
//  Copyright © 2016年 www.hd123.com. All rights reserved.
//

import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l > r
  default:
    return rhs < lhs
  }
}


class Client_RF225_qArticleController: HDFounctionBaseController , HDBarcodeInputCellInputDelegate , HDFounctionBottomViewDelegate{
//    //MARK: - property
    var firstAppear: Bool = true
    var dataArray0:[[String : String]] = [["title" : "货品条码"] , ["title" :"货品代码"], ["title" : "货品名称"]]
    var dataArray1:[[String : String]]?{
        didSet{
            self.tableView.reloadData()
        }
    }
    var dataArray2:[[String : String]]?{
        didSet{
            self.tableView.reloadData()
        }
    }

    //MARK: - lifeCycle
    override func viewDidLoad() {
        self.tableView.register(HDBarcodeInputCell.self, forCellReuseIdentifier: "HDBarcodeInputCell")
        self.tableView.register(HDProductInfocell.self, forCellReuseIdentifier: "HDProductInfocell")
        self.tableView.register(HDKeyboardInputCell.self, forCellReuseIdentifier: "HDKeyboardInputCell")
        self.tableView.register(HDBinSpecTableviewCell.self, forCellReuseIdentifier: "HDBinSpecTableviewCell")
        self.tableView.register(HDChkBinInfoTableviewCell.self, forCellReuseIdentifier: "HDChkBinInfoTableviewCell")
        super.viewDidLoad()
        self.tableView.allowsSelection = true
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if self.firstAppear == true{
            let indexPath = IndexPath(row: 0, section: 0)
            let cell = self.tableView.cellForRow(at: indexPath) as! HDBarcodeInputCell
            UIView.animate(withDuration: Double((indexPath as NSIndexPath).row) * 0.1, animations: {
                self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.top, animated: false)
                }, completion: { (true) in
                    cell.state = inputViewState.activated
            })
            self.firstAppear = false
        }
    }
    //MARK: - delegate
    func clickFounctionBottom(_ position: NSInteger) {
        let time = Double((self.tableView.contentOffset.y / KscreenHeight) * 0.5)
        let timeToRun = time > 1.2 ? 1.2 : time
        UIView.animate(withDuration: timeToRun, animations: {
//            self.tableView.contentOffset.y = 20
            self.tableView.scrollToRow(at: IndexPath(item: 0 , section: 0), at: UITableViewScrollPosition.top, animated: false)
            }, completion: { (true) in
                let cell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! HDBarcodeInputCell
                self.clicKReturn(cell)
        }) 
    }
    func clicKReturn(_ cell: HDBarcodeInputCell) {
        let celltext = cell.codeInputView.textField.text
        if celltext?.characters.count == 0 {
            self.showMessage("请输入货品条码", success: false)
            return
        }
        self.oneToManyHandler(celltext!, piOwner: "-1", piBin: nil, success: { (dict) in
            self.getCollection(["piArticle" : dict["内码"]!], bodyMethod: "qryArticle", suffix: nil, success: { (dict, collections) in
                cell.codeInputView.textField.text = nil
                let originString = dict["poPickInfo"]
                let stringArray = originString?.components(separatedBy: "--")
                guard stringArray?.count > 0 else{
                    return
                }
                var tempArray = [[String : String]]()
                for text in stringArray! {
                    let dataDict = [
                        "left" : self.getStringBettwen("方案代码：", textRight: "拣货规格：", inString: text) ?? "",
                        "middle" : self.getStringBettwen("拣货规格：", textRight: "拣货位：", inString: text) ?? "",
                        "right" : self.getStringBettwen("拣货位：", textRight: "", inString: text) ?? ""
                    ]
                    tempArray.append(dataDict)
                }
                self.dataArray0[1].updateValue(dict["poArticleCode"]!, forKey: "text")
                self.dataArray0[2].updateValue(dict["poArticleName"]!, forKey: "text")
                self.dataArray1 = tempArray
                self.dataArray2 = collections
                }, failed: {
                  cell.state = inputViewState.wrong
            })
        }){
            cell.state = inputViewState.wrong
        }
    }
    //MARK: - private
    func getStringBettwen(_ textLeft: String , textRight: String , inString: String) -> (String?){
        let string1 = inString.components(separatedBy: textLeft).last
//        if textRight == ""{
//        }
        guard string1 != nil else{
            return nil
        }
        let string2 = string1!.components(separatedBy: textRight).first
        return string2
    }
    override func isEmpty() -> (Bool) {
        if dataArray1?.count > 0 {
            return false
        }else{
            return true
        }
    }
    //MARK: - tableviewDatasource
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 3
        case 1:
            return dataArray1?.count ?? 1
        case 2:
            return dataArray2?.count ?? 1
        default:
            return 0
        }
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellOriginal:HDFounctionBaseCell?
        switch ((indexPath as NSIndexPath).section) * 1000 + ((indexPath as NSIndexPath).row) {
        case 0:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDBarcodeInputCell") as! HDBarcodeInputCell
            let cell = cellOriginal as! HDBarcodeInputCell
            cell.titleView.text = "货品条码"
            cell.InputDelegate = self
        case 1...2:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDProductInfocell") as! HDProductInfocell
            cellOriginal!.info = self.dataArray0[(indexPath as NSIndexPath).row]
        case 1000...1999:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDChkBinInfoTableviewCell") as! HDChkBinInfoTableviewCell
            let cell = cellOriginal as! HDChkBinInfoTableviewCell
            if let dataArr = dataArray1{
                cell.dict = dataArr[(indexPath as NSIndexPath).row]
            }else{
                cell.dict = ["middle" : "无数据"]
            }
        case 2000...2999:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDBinSpecTableviewCell") as! HDBinSpecTableviewCell
            let cell = cellOriginal as! HDBinSpecTableviewCell
            if let dataArr = dataArray2{
                var dict = dataArr[(indexPath as NSIndexPath).row]
                dict.updateValue(dict["货位"] ?? "", forKey: "left")
                dict.updateValue(dict["规格"] ?? "", forKey: "middle")
                dict.updateValue(dict["件数"] ?? "", forKey: "right")
                cell.dict = dict
            }
        default:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDProductInfocell") as! HDProductInfocell
        }
        if !self.reuseFlag {
            cellOriginal?.clearContent()
        }
        return cellOriginal!
    }

    //MARK: - tableViewDelegate
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (indexPath as NSIndexPath).section == 2 && dataArray2 != nil {
            let dict = self.dataArray2![(indexPath as NSIndexPath).row]
            let vc = binDetailTableViewController(info: dict)
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        //           let sectionHeaders:[String] = [,]
        switch section {
        case 1:
            let view = FounctionSectionHeaderView(headerString: "方案代码,拣货位,规格")
            return view
        case 2:
            let view = FounctionSectionHeaderView(headerString: "货位,规格,件数")
            return view
        default:
            return nil
        }
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return 10
        case 1,2:
            return HDFSectionHeadrHeight
        default:
            return 0
        }
    }
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
}
